"""
基础仓储类
提供通用的CRUD操作
"""
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy import select, update, delete, func, and_, or_
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.core.database import Base

ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)


class BaseRepository(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
    """基础仓储类"""
    
    def __init__(self, model: Type[ModelType]):
        """
        初始化仓储
        Args:
            model: SQLAlchemy模型类
        """
        self.model = model
    
    async def get(self, db: AsyncSession, id: Any) -> Optional[ModelType]:
        """
        根据ID获取单个对象
        Args:
            db: 数据库会话
            id: 对象ID
        Returns:
            模型对象或None
        """
        stmt = select(self.model).where(self.model.id == id)
        result = await db.execute(stmt)
        return result.scalar_one_or_none()
    
    async def get_multi(
        self,
        db: AsyncSession,
        *,
        skip: int = 0,
        limit: int = 100,
        filters: Optional[Dict[str, Any]] = None,
        order_by: Optional[str] = None,
        order_desc: bool = True
    ) -> List[ModelType]:
        """
        获取多个对象
        Args:
            db: 数据库会话
            skip: 跳过数量
            limit: 限制数量
            filters: 过滤条件
            order_by: 排序字段
            order_desc: 是否降序
        Returns:
            模型对象列表
        """
        stmt = select(self.model)
        
        # 应用过滤条件
        if filters:
            for field, value in filters.items():
                if hasattr(self.model, field):
                    if isinstance(value, list):
                        stmt = stmt.where(getattr(self.model, field).in_(value))
                    elif isinstance(value, dict):
                        # 支持范围查询
                        if "gte" in value:
                            stmt = stmt.where(getattr(self.model, field) >= value["gte"])
                        if "lte" in value:
                            stmt = stmt.where(getattr(self.model, field) <= value["lte"])
                        if "like" in value:
                            stmt = stmt.where(getattr(self.model, field).like(f"%{value['like']}%"))
                    else:
                        stmt = stmt.where(getattr(self.model, field) == value)
        
        # 应用排序
        if order_by and hasattr(self.model, order_by):
            order_field = getattr(self.model, order_by)
            if order_desc:
                stmt = stmt.order_by(order_field.desc())
            else:
                stmt = stmt.order_by(order_field.asc())
        else:
            # 默认按创建时间降序
            if hasattr(self.model, "created_at"):
                stmt = stmt.order_by(self.model.created_at.desc())
        
        # 应用分页
        stmt = stmt.offset(skip).limit(limit)
        
        result = await db.execute(stmt)
        return result.scalars().all()
    
    async def count(
        self,
        db: AsyncSession,
        filters: Optional[Dict[str, Any]] = None
    ) -> int:
        """
        统计对象数量
        Args:
            db: 数据库会话
            filters: 过滤条件
        Returns:
            对象数量
        """
        stmt = select(func.count(self.model.id))
        
        # 应用过滤条件
        if filters:
            for field, value in filters.items():
                if hasattr(self.model, field):
                    if isinstance(value, list):
                        stmt = stmt.where(getattr(self.model, field).in_(value))
                    elif isinstance(value, dict):
                        if "gte" in value:
                            stmt = stmt.where(getattr(self.model, field) >= value["gte"])
                        if "lte" in value:
                            stmt = stmt.where(getattr(self.model, field) <= value["lte"])
                        if "like" in value:
                            stmt = stmt.where(getattr(self.model, field).like(f"%{value['like']}%"))
                    else:
                        stmt = stmt.where(getattr(self.model, field) == value)
        
        result = await db.execute(stmt)
        return result.scalar()
    
    async def create(self, db: AsyncSession, *, obj_in: CreateSchemaType) -> ModelType:
        """
        创建对象
        Args:
            db: 数据库会话
            obj_in: 创建数据
        Returns:
            创建的模型对象
        """
        obj_in_data = jsonable_encoder(obj_in)
        db_obj = self.model(**obj_in_data)
        db.add(db_obj)
        await db.commit()
        await db.refresh(db_obj)
        return db_obj
    
    async def update(
        self,
        db: AsyncSession,
        *,
        db_obj: ModelType,
        obj_in: Union[UpdateSchemaType, Dict[str, Any]]
    ) -> ModelType:
        """
        更新对象
        Args:
            db: 数据库会话
            db_obj: 数据库对象
            obj_in: 更新数据
        Returns:
            更新后的模型对象
        """
        obj_data = jsonable_encoder(db_obj)
        if isinstance(obj_in, dict):
            update_data = obj_in
        else:
            update_data = obj_in.dict(exclude_unset=True)
        
        for field in obj_data:
            if field in update_data:
                setattr(db_obj, field, update_data[field])
        
        db.add(db_obj)
        await db.commit()
        await db.refresh(db_obj)
        return db_obj
    
    async def delete(self, db: AsyncSession, *, id: int) -> ModelType:
        """
        删除对象
        Args:
            db: 数据库会话
            id: 对象ID
        Returns:
            删除的模型对象
        """
        obj = await self.get(db=db, id=id)
        if obj:
            await db.delete(obj)
            await db.commit()
        return obj
    
    async def exists(self, db: AsyncSession, **kwargs) -> bool:
        """
        检查对象是否存在
        Args:
            db: 数据库会话
            **kwargs: 查询条件
        Returns:
            是否存在
        """
        stmt = select(self.model.id)
        for field, value in kwargs.items():
            if hasattr(self.model, field):
                stmt = stmt.where(getattr(self.model, field) == value)
        
        result = await db.execute(stmt)
        return result.scalar_one_or_none() is not None
    
    async def get_by_field(
        self,
        db: AsyncSession,
        field_name: str,
        field_value: Any
    ) -> Optional[ModelType]:
        """
        根据字段值获取对象
        Args:
            db: 数据库会话
            field_name: 字段名
            field_value: 字段值
        Returns:
            模型对象或None
        """
        if not hasattr(self.model, field_name):
            return None
        
        stmt = select(self.model).where(getattr(self.model, field_name) == field_value)
        result = await db.execute(stmt)
        return result.scalar_one_or_none()
    
    async def bulk_create(
        self,
        db: AsyncSession,
        *,
        objs_in: List[CreateSchemaType]
    ) -> List[ModelType]:
        """
        批量创建对象
        Args:
            db: 数据库会话
            objs_in: 创建数据列表
        Returns:
            创建的模型对象列表
        """
        db_objs = []
        for obj_in in objs_in:
            obj_in_data = jsonable_encoder(obj_in)
            db_obj = self.model(**obj_in_data)
            db_objs.append(db_obj)
            db.add(db_obj)
        
        await db.commit()
        for db_obj in db_objs:
            await db.refresh(db_obj)
        
        return db_objs
    
    async def bulk_update(
        self,
        db: AsyncSession,
        *,
        updates: List[Dict[str, Any]]
    ) -> int:
        """
        批量更新对象
        Args:
            db: 数据库会话
            updates: 更新数据列表，每个字典必须包含id字段
        Returns:
            更新的对象数量
        """
        updated_count = 0
        for update_data in updates:
            if "id" not in update_data:
                continue
            
            obj_id = update_data.pop("id")
            stmt = update(self.model).where(self.model.id == obj_id).values(**update_data)
            result = await db.execute(stmt)
            updated_count += result.rowcount
        
        await db.commit()
        return updated_count